package com.hsource.common.utils;



import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @classname:
 */

public class DateUtil {

	public static String atime() throws ParseException {
		Calendar cal=Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date date = sdf.parse("1970-01-01 00:00:00");
		cal.setTime(date);
		Calendar cal1=Calendar.getInstance();
		return String.valueOf((cal1.getTime().getTime()-cal.getTime().getTime())/1000);
	}

	/**
	 * 计算年龄
	 * @param birthDay 生日
	 * @return
	 * @throws Exception
	 */
	public static  int getAge(Date birthDay) throws Exception {
		Calendar cal = Calendar.getInstance();
		if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
			throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
		}
		int yearNow = cal.get(Calendar.YEAR);  //当前年份
		int monthNow = cal.get(Calendar.MONTH);  //当前月份
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
		cal.setTime(birthDay);
		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH);
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
		int age = yearNow - yearBirth;   //计算整岁数
		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth) {
				if (dayOfMonthNow < dayOfMonthBirth) {
					age--;
				}
			}else{
				age--;//当前月份在生日之前，年龄减一
			}
		}
		return age;
	}

	/**
	 * 把时间戳转换成Corn表达式 (在某个固定时间点执行动作)
	 */
	public static String timestampToCorn(String time, String week) {
		// 时间格式: <!-- s m h d m w(?) y(?) -->, 分别对应: 秒>分>小时>日>月>周>年,
		String corn = "";
		String ss, mm, HH, dd, MM, yyyy;
		ss = time.substring(17, 19);
		mm = time.substring(14, 16);
		HH = time.substring(11, 13);
		dd = "*";
		MM = "*";
		yyyy = "?";
		corn = ss + " " + mm + " " + HH + " " + ("".equals(week) ? dd : "?") + " " + MM + " "
				+ ("".equals(week) ? "" : (week + "")) + ("".equals(week) ? yyyy : "");

		return corn;
	}

	/**
	 * 获取日志之间小时差
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static int getDifferenceHourIndex(Date startDate, Date endDate,int hourinterval){

		long nh = 1000 * 60 * 60;

		long diff = endDate.getTime() - startDate.getTime();
		long hour = (diff / nh / hourinterval);

		return (int) hour;
	}
	public static int getDifferenceDayIndex(Date startDate,Date endDate){

		long nd = 1000 * 24 * 60 * 60;

		long diff = endDate.getTime() - startDate.getTime();
		long day = (diff / nd+1);

		return (int) day;
	}
	/**
	 *
	 * 描述:获取下一个月.
	 *
	 * @return
	 */
	public static Date getPreMonth() {
		Calendar cal = Calendar.getInstance();
		cal.add(cal.MONTH, 1);
		return cal.getTime();
	}

	/**
	 * 获取当年的最后一天
	 * @return
	 */
	public static Date getCurrYearLast(){
		Calendar currCal=Calendar.getInstance();
		int currentYear = currCal.get(Calendar.YEAR);
		return getYearLast(currentYear);
	}
	/**
	 * 获取当年的第一天
	 * @return
	 */
	public static Date getCurrYearFirst(){
		Calendar currCal=Calendar.getInstance();
		int currentYear = currCal.get(Calendar.YEAR);
		return getYearFirst(currentYear);
	}

	/**
	 * 获取某年最后一天日期
	 * @param year
	 * @return
	 */
	public static Date getYearLast(int year){
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		calendar.roll(Calendar.DAY_OF_YEAR, -1);
		Date currYearLast = calendar.getTime();
		return currYearLast;
	}
	/**
	 * 获取某年第一天日期
	 * @param year
	 * @return
	 */
	public static Date getYearFirst(int year){
		Calendar calendar=Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR,year);
		Date currYearFirst=calendar.getTime();
		return currYearFirst;
	}

	/**
	* ��õ�ǰʱ��
	* @param parrten �����ʱ���ʽ
	* @return ����ʱ��
	*/
	public static String getTime(String parrten){
		String timestr;
		if(parrten==null||parrten.equals("")){
			parrten="yyyyMMddHHmmss";
		}
		SimpleDateFormat sdf=new SimpleDateFormat(parrten);
		Date cday=new Date();
		timestr=sdf.format(cday);
		return timestr;
	}
	
	/**
	* ��õ�ǰʱ��
	* @param parrten �����ʱ���ʽ
	* @return ����ʱ��
	*/
	public static String getPreWeekTime(String parrten){
		String timestr;
		if(parrten==null||parrten.equals("")){
			parrten="yyyyMMddHHmmss";
		}
		SimpleDateFormat sdf=new SimpleDateFormat(parrten);
		Calendar cl= Calendar.getInstance();
		cl.add(Calendar.MONTH,-1);
		Date preWeekDate=cl.getTime();
		
		timestr=sdf.format(preWeekDate);	
		return timestr;
	}
	
	/**
	* @see ��õ�ǰʱ��
	* @return Date date
	*/
	public static Date getNOWTime() {
	   
       SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
       String curTime=getTime("yyyy-MM-dd HH:mm:ss"); 
       Date curdate = null;
	   try {
			curdate = df.parse(curTime);
	   } catch (ParseException e) {			
			e.printStackTrace();
		}   
	   return curdate;
	}

	/**
	* ��ݵ�ǰʱ���ȡ�����
	* @return �����
	*/
	public static String getTimeRandomOld(){
        String strRandom=null;
        Date date = new Date();
        int hour=getHour(date);
        int min=getMinute(date);
        int second=getSecond(date);
        int milsec=getMillSecond(date);
        
        for (int i=1;i<10;i++){
	        int intRandom=i*(hour+1)*(min+1)*(second+1)*(milsec+1);
	        strRandom=Integer.toString(intRandom); 
        } 
		return strRandom;
	}
	/**
	* ��ȡ6λ�����
	* @return �����
	* added by bh  2010/5/7
	*/	
    public static String getTimeRandom(){  		
	    List<Integer> list = new ArrayList<Integer>();  		
	    Random random = new Random();  		
	    while (true) {  			 
			int randomNum = random.nextInt(10);
			boolean flag = false; 
			for(Integer in : list){
				if(in == randomNum){  		
					  flag = true;  					
					  break;  				
				}  	
			}  			 
			if(!flag){  				
			  	list.add(randomNum);  		
			}  			 
			if(list.size()==6){  
			  	break;  		
			}  
	    }  		
		String randomStr = "";  
		for (Integer in : list) {  			
			randomStr  = randomStr + in.toString();
		}  		
		return randomStr;  	
   } 
	
	/**
	 * �������
	 * @param date    ����
	 * @return �������
	 */
	public static int getYear(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.YEAR);
	}

	/**
	 * �����·�
	 * @param date����
	 * @return �����·�
	 */
	public static int getMonth(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.MONTH) + 1;
	}
	
	/**
	 * ������
	 * @param date����
	 * @return ������
	 */
	public static int getDay(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
        return   c.get(Calendar.DAY_OF_MONTH); 
    } 
	/**
	 * ����Сʱ
	 * @param date����
	 * @return ����Сʱ
	 */
	public static int getHour(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
        return   c.get(Calendar.HOUR_OF_DAY); 
    } 
	/**
	 * ���ط���
	 * @param date����
	 * @return ���ط���
	 */
	public static int getMinute(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
        return   c.get(Calendar.MINUTE); 
    }
	
	/**
	 * ������
	 * @param date����
	 * @return ������
	 */
	public static int getSecond(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
        return   c.get(Calendar.SECOND); 
    }
	/**
	 * ���غ���
	 * @param date����
	 * @return ���غ���
	 */
	public static int getMillSecond(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
        return   c.get(Calendar.MILLISECOND); 
    }
	
	/**
	 * ���ַ�2008-07-10 19:20:00����һ��Date���͵����
	 */
	
	public static Date	strToDateLong(String strDate) {
		
		SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ParsePosition pos=new ParsePosition(0);
		Date strtodate=formatter.parse(strDate,pos);
		return strtodate;
    }
	
	/**
     * ʱ��ת��Ϊ�ַ�
	*/
	public static String getStrFromDate(Date date,String pattern){
		try{
			String result="";
			
			if(pattern==null||pattern.equals("")){
				pattern="yyyy-MM-dd HH:mm:ss";
			}
			
			SimpleDateFormat df = new SimpleDateFormat(pattern);
			result=df.format(date);

	        return result;
		}
        catch (Exception ex) {
            return "";
        }
	}
    public static void main(String[] args) throws ParseException {
    	/*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	System.out.println("字符串====="+getStrFromDate(getNOWTime(), null));
    	System.out.println("转换date===="+sdf.parse(getStrFromDate(getNOWTime(), null)));*/

		Date data=getDateFromStr("2019-10-11 05:00:00","yyyy-MM-dd HH:mm:ss");
		System.out.println(data);
	}
    /**
	* �ַ�ת����ʱ��
	* @return Date date
	*/
    public static Date getDateFromStr(String dateStr,String pattern) {
    	
    	try{
    		if(pattern==null||pattern.equals("")){
    			pattern="yyyy-MM-dd HH:mm:ss";
    		}
    		
    		SimpleDateFormat df = new SimpleDateFormat(pattern);
    		Date date = df.parse(dateStr);
    		return date;
    	}
    	catch (Exception ex) {
            return null;
        }
	}

    /**
     * ��ȡ����ʱ��ĵ������һ��
     * monthnum=0��ʾ�������һ��
	*/
    public static Date getLastDayOfMonth(Date date,int monthnum){
		try{
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.set(Calendar.DAY_OF_MONTH, 1);
			cal.add(Calendar.MONTH, monthnum+1);
			cal.add(Calendar.DATE, -1);
			return cal.getTime();
		}
        catch (Exception ex) {
            return null;
        }
	}
	/**计算两个时间相差天数**/
	public static int calcDayOffset(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date1);

		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(date2);
		int day1 = cal1.get(Calendar.DAY_OF_YEAR);
		int day2 = cal2.get(Calendar.DAY_OF_YEAR);

		int year1 = cal1.get(Calendar.YEAR);
		int year2 = cal2.get(Calendar.YEAR);
		if (year1 != year2) {  //同一年
			int timeDistance = 0;
			for (int i = year1; i < year2; i++) {
				if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {  //闰年
					timeDistance += 366;
				} else {  //不是闰年

					timeDistance += 365;
				}
			}
			return timeDistance + (day2 - day1);
		} else { //不同年
			return day2 - day1;
		}
	}


    /**
     * ��ȡ����ʱ��ĵ��µ�һ��
     * monthnum=0��ʾ���µ�һ��
	*/
    public static Date getFirstDayOfMonth(Date date,int monthnum){
		try{
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.set(Calendar.DAY_OF_MONTH, 1);
			cal.add(Calendar.MONTH, monthnum);
			return cal.getTime();
		}
        catch (Exception ex) {
            return null;
        }
	}
    
    /**
     * ��ȡ����ʱ��֮�������·���
     * ��鵽�·ݣ��������
     * endDate��=startDate
	*/
    @SuppressWarnings("finally")
	public static int diffMonth(Date startDate, Date endDate) throws Exception {
    	
    	int result = 0;
    	
    	try{
    		SimpleDateFormat df = new SimpleDateFormat("yyyy");
			int year1 = Integer.parseInt(df.format(startDate));
			int year2 = Integer.parseInt(df.format(endDate));
			
			df = new SimpleDateFormat("MM");
			int month1 = Integer.parseInt(df.format(startDate));
			int month2 = Integer.parseInt(df.format(endDate));
			
			result = (year2-year1)*12+month2-month1;
    		
    	}catch (Exception ex) {
            
        }finally{
    		return result;
    	}
	}

	public static boolean  eqTime(String time1,String time2){


		//比较时间大小
		int tm = time1.compareTo(time2);
		if (tm < 0) {//小于time2
           return false;
		}
		return true;
	}

	/**返回年月日字符串*/
	public static String   dailyTimeStr(){

		return DateUtil.getStrFromDate(Calendar.getInstance().getTime(), "yyyy-MM-dd") ;

	}

}